#include <iostream>
#include <curl/curl.h>
#include <string>
#include <map>
#include "Transcoding.h"

using namespace std;

//回调函数得到响应内容
int write_data(char* buffer, size_t size, size_t nmemb, void* userp) {
	std::string * str = dynamic_cast<std::string *>((std::string *)userp);
	str->append((char *)buffer, size * nmemb);
	return nmemb;
}

int posts(string url, string &body, string* response);
int get(string url, string* response);

int get(string url, string* response)
{
	CURL *curl;
	CURLcode ret;
	struct curl_slist *headers = NULL;
	headers = curl_slist_append(headers, "Content-Type:application/x-www-form-urlencoded;charset=UTF-8");
	curl = curl_easy_init();    // 初始化

	if (curl)
	{
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);        //改协议头
		curl_easy_setopt(curl, CURLOPT_URL, (char *)url.c_str());   // 指定url
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)response);
		int status_code = curl_easy_perform(curl);   // 执行


		ret = curl_easy_perform(curl);                          //执行请求
		if (ret == 0) {
			curl_slist_free_all(headers);
			curl_easy_cleanup(curl);
			return status_code;
		}
		else {
			return ret;
		}
	}
	else {
		return -1;
	}
}

int posts(string url, string &body, string* response)
{
	CURL *curl;
	CURLcode ret;
	curl = curl_easy_init();
	long response_code = 0;
	if (curl)
	{
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());           //指定post内容
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, body.size());         //指定post长度
		curl_easy_setopt(curl, CURLOPT_HEADER, 0);                          //设置协议头
		// curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
		curl_easy_setopt(curl, CURLOPT_URL, (char *)url.c_str());           //指定url
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);          //绑定相应
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)response);        //绑定响应内容的地址
		ret = curl_easy_perform(curl);										//执行请求
		if (ret == 0) {
			curl_easy_cleanup(curl);
			curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);//获取http 状态码 
			return 0;
		}
		else {
			curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);//获取http 状态码
			return ret;
		}
	}
	else 
	{
		return -1;
	}
}

//int main(int argc, char** argv) {
//	std::map<std::string, std::string> data;
//	std::string body;
//
//	std::string response;
//	int status_code;
//
//	////get
//	status_code = get("http://www.baidu.com", &response);
//	if (status_code != CURLcode::CURLE_OK) {
//		return -1;
//	}
//	cout << Transcoding::UTF8ToGBK(response.c_str()) << endl;
//
//	//post
//	response = "";
//	status_code = posts("http://v.juhe.cn/weather/index", body, &response);
//	if (status_code != CURLcode::CURLE_OK) {
//		return -1;
//	}
//	cout << Transcoding::UTF8ToGBK(response.c_str()) << endl;
//
//	return 0;
//}